<script setup lang="ts">
import { requiredCheck, singleIpCheck, singleIpCheckFun, validatePortFun } from "@/utils/verify";
import { ref } from "vue";
import { ifaceAttrGet, ifaceAttrSet, subifaceAdd } from "@/api/modules/dynamic-camouflage/line-config";
import { ElMessage } from "element-plus";

interface Props {
  title?: string;
  rowData?: Object;
  links?: Object;
}

const props = withDefaults(defineProps<Props>(), {
  title: "网络配置",
  rowData: undefined,
  links: []
});
defineOptions({
  name: "UpdateForm" // 默认策略
});
import useUpdate from "@/hooks/useUpdate";
import { ifaceAll, ifacemodeUpdate } from "@/api/modules/dynamic-camouflage/line-config";
import { addData, editData } from "@/api/modules/dynamic-camouflage/sentinel-config";

const emits = defineEmits(["success"]);
const { updateFormData, updateFormRef, updateFormRules, submit, showHandle, openHandle, closeHandle } = useUpdate({
  rules: {
    ip: [...requiredCheck("请输入网关"), { validator: singleIpCheck }],
    lan_ip: [
      ...requiredCheck("请输入虚拟网段"),
      {
        validator: (rule, value, callback) => {
          function ipToInt(ip) {
            if (!ip) return false;
            return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
          }

          if (updateFormData.bootproto == 1) {
            if (singleIpCheckFun(updateFormData.lan_ip_one) && singleIpCheckFun(updateFormData.lan_ip_two)) {
              if (ipToInt(updateFormData.lan_ip_one) > ipToInt(updateFormData.lan_ip_two)) {
                callback("网段格式错误");
              } else {
                callback();
              }
            } else {
              callback("IP格式错误");
            }
          } else {
            if (singleIpCheckFun(updateFormData.lan_ip_one)) {
              callback();
            } else {
              callback("IP格式错误");
            }
          }
        }
      }
    ],
    ga_ip: [
      ...requiredCheck("请输入网关"),
      {
        validator: (rule, value, callback) => {
          function ipToInt(ip) {
            if (!ip) return false;
            return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0);
          }

          if (updateFormData.bootproto == 1) {
            if (singleIpCheckFun(updateFormData.ga_ip_one) && singleIpCheckFun(updateFormData.ga_ip_two)) {
              if (ipToInt(updateFormData.ga_ip_one) > ipToInt(updateFormData.ga_ip_two)) {
                callback("网段格式错误");
              } else {
                callback();
              }
            } else {
              callback("IP格式错误");
            }
          } else {
            if (singleIpCheckFun(updateFormData.ga_ip_one)) {
              callback();
            } else {
              callback("IP格式错误");
            }
          }
        }
      }
    ],
    wan_ip: [...requiredCheck("IP不能为空"), { validator: singleIpCheck }],
    lan_ip_one: [...requiredCheck("虚拟网段不能为空"), { validator: singleIpCheck }],
    mask: [...requiredCheck("掩码不能为空"), { validator: singleIpCheck }],
    gateway: [...requiredCheck("网关不能为空"), { validator: singleIpCheck }]
  },
  defaultData: {
    bootproto: "1",
    destport: "0-65535"
  }
});

function ipToLong(ip) {
  if (!ip) return;
  return ip.split(".").reduce((acc, octet) => {
    return (acc << 8) + parseInt(octet, 10);
  }, 0);
}

function countSubnets(startIP, endIP) {
  const start = ipToLong(startIP);
  const end = ipToLong(endIP);

  if (start > end) {
    return 0; // 如果起始 IP 大于结束 IP，返回 0
  }

  // 计算起始和结束 IP 之间的差
  const totalIPs = end - start + 1;

  // 计算总网段数，每个网段可以容纳 256 个 IP
  // 这里假设我们以 /24 网段为单位，也就是每个网段 256 个 IP
  const subnets = Math.ceil(totalIPs / 256);

  return subnets;
}

function longToIp(long) {
  return [(long >> 24) & 255, (long >> 16) & 255, (long >> 8) & 255, long & 255].join(".");
}

function calculateNewSubnets(startIP, numberOfSubnets) {
  const startLong = ipToLong(startIP);
  const baseSubnet = startLong & 0xffffff00; // 将 IP 地址转为网段的基地址

  const newSubnets = [];
  for (let i = 0; i < numberOfSubnets; i++) {
    const newSubnet = baseSubnet + i * 256; // 每个网段增加 256
    newSubnets.push(longToIp(newSubnet));
  }
  if (newSubnets.length) {
    return newSubnets[newSubnets.length - 1];
  }
  return newSubnets;
}

async function submitCb() {
  await updateFormRef.value.validate();
  console.log(props.rowData)
  let ifid = props.rowData.ifid;
  const lanIfid = ifid.split("-")[0];
  const wanIfid = ifid.split("-")[1];
  // ===============================wan口更新
  // {"ifid":"5","bootproto":"1","ip":"12.23.23.1","mask":"255.255.255.0","number":1,"gateway":"12.23.23.1"}
  await ifaceAttrSet({
    ifid: wanIfid,
    bootproto: "1",
    number: 1,
    ip: updateFormData.wan_ip,
    mask: updateFormData.mask,
    gateway: updateFormData.gateway
  });
  await subifaceAdd([
    {
      ifid: wanIfid,
      name: `${props.rowData.wan}-0`,
      vlanid: "0",
      type: "1",
      iprange: "",
      destport: "0-65535",
      cfg: { ip: updateFormData.wan_ip, mask: updateFormData.mask, bootproto: "1" }
    }
  ]);
  // ======================lan口更新
  //静态： {"ifid":"4","bootproto":"1","number":13,"ip":"12.23.23.1/24","transformation":"1","vstatic":"23.23.23.0/24-23.23.35.0/24","vdyn":"34.23.23.0/24"}
  //动态： {"ip":"12.23.23.0-12.23.32.0","ifid":"4","bootproto":"2","number":10,"transformation":"1","vstatic":"12.33.23.0/24","vdyn":"23.1.12.0/24"}
  let lanIp = "";
  let lanNumber = 0;
  if (updateFormData.bootproto == 1) {
    lanNumber = countSubnets(updateFormData.lan_ip_one, updateFormData.lan_ip_two);
  } else {
    lanNumber = countSubnets(updateFormData.ga_ip_one, updateFormData.ga_ip_two);
  }
  if (updateFormData.bootproto == 1) {
    let ipArr = updateFormData.ip.split(".");
    lanIp = `${ipArr[0]}.${ipArr[1]}.${ipArr[2]}.1` + "/24";
  } else {
    let ipArrOne = updateFormData.ga_ip_one.split(".");
    let ipArrTwo = updateFormData.ga_ip_two.split(".");
    lanIp = `${ipArrOne[0]}.${ipArrOne[1]}.${ipArrOne[2]}.0-${ipArrTwo[0]}.${ipArrTwo[1]}.${ipArrTwo[2]}.0`;
  }
  console.log(lanNumber);
  let vstatic = "";
  if (updateFormData.bootproto == 1) {
    let ipOne = updateFormData.lan_ip_one.split(".");
    let ipTwo = updateFormData.lan_ip_two.split(".");
    vstatic = `${ipOne[0]}.${ipOne[1]}.${ipOne[2]}.0/24-${ipTwo[0]}.${ipTwo[1]}.${ipTwo[2]}.0/24`;
  } else {
    let ipOne = updateFormData.lan_ip_one.split(".");
    vstatic = `${ipOne[0]}.${ipOne[1]}.${ipOne[2]}.0/24`;
  }
  let vdyn = "";
  let vdynStr = updateFormData.wan_ip.split(".");
  vdyn = `${vdynStr[0]}.${vdynStr[1]}.${vdynStr[2]}.0/24`;
  await ifaceAttrSet({
    ifid: lanIfid,
    bootproto: updateFormData.bootproto,
    number: lanNumber,
    ip: lanIp,
    transformation: "1",
    vstatic: vstatic,
    vdyn
  });

  showHandle.value = false;
  ElMessage.success("保存成功");
  emits("success");
}

function openCb() {
  openHandle({
    row: {
      ...props.rowData
    },
    id: props.rowData?.id
  });
  console.log("rops.ifid", props.rowData.ifid);
  if (props.rowData.ifid) {
    getData();
  }
}

async function getData() {
  const lanIfid = props.rowData.ifid.split("-")[0];
  const wanIfid = props.rowData.ifid.split("-")[1];
  console.log("lanIfid");
  console.log("lanIfid");
  const [res1, res2] = await Promise.all([ifaceAttrGet({ ifid: lanIfid }), ifaceAttrGet({ ifid: wanIfid })]);
  console.log(res1);
  console.log(res2);
  //   =========================wan
  updateFormData.gateway = res2.gateway;
  updateFormData.mask = res2.mask;
  updateFormData.wan_ip = res2.ip;
  updateFormData.bootproto = res1.bootproto;
  if (res1.bootproto == 1) {
    // 静态
    let ipAttr = res1.ip.split("/");
    updateFormData.ip = ipAttr[0];
    let vstaticAttr = res1.vstatic.split("-");
    let vstaticOneAttr = vstaticAttr[0].split("/");
    let vstaticTwoAttr = vstaticAttr[1].split("/");
    updateFormData.lan_ip_one = vstaticOneAttr[0];
    updateFormData.lan_ip_two = vstaticTwoAttr[0];
    updateFormData.lan_ip = updateFormData.lan_ip_one + updateFormData.lan_ip_two;
  } else {
    //动态
    let ipAttr = res1.ip.split("-");
    updateFormData.ga_ip_one = ipAttr[0];
    updateFormData.ga_ip_two = ipAttr[1];
    updateFormData.ga_ip = ipAttr[0] + ipAttr[1];
    let vstaticAttr = res1.vstatic.split("/");
    updateFormData.lan_ip_one = vstaticAttr[0];
  }
}

function modeChange() {
  updateFormData.ip = "";
  updateFormData.lan_ip_one = "";
  updateFormData.lan_ip_two = "";
  updateFormData.lan_ip = "";
  updateFormData.ga_ip_one = "";
  updateFormData.ga_ip_two = "";
  updateFormData.ga_ip = "";
}
</script>

<template>
  <div class="update-form mg-r-sm" style="display: inline-block" @click="openCb">
    <slot>
      <el-button class="mg-r-sm" type="primary">新增</el-button>
    </slot>
  </div>
  <base-dialog @confirm="submitCb()" width="550px" :title="title" v-model="showHandle">
    <div class="details">
      <div class="details-main">
        <el-form ref="updateFormRef" :model="updateFormData" :rules="updateFormRules" label-width="100px" label-suffix="：">
          <div style="font-size: 18px; margin-left: 25px">LAN</div>
          <div class="h-box mg-t-lg">
            <el-form-item label="模式" prop="bootproto">
              <el-select @change="modeChange" style="width: 130px" v-model="updateFormData.bootproto" placeholder="请选择模式">
                <el-option label="静态" value="1"></el-option>
                <el-option label="动态" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="updateFormData.bootproto == 1" label="网关" prop="ip">
              <el-input style="width: 130px" v-model="updateFormData.ip" placeholder="请输入网关"></el-input>
            </el-form-item>
            <el-form-item v-else label="虚拟网段" prop="lan_ip_one">
              <el-input style="width: 130px" v-model="updateFormData.lan_ip_one" placeholder="请输入虚拟网段"></el-input>
              /24
            </el-form-item>
          </div>

          <el-form-item label="虚拟网段" prop="lan_ip" v-if="updateFormData.bootproto == 1">
            <div class="h-box">
              <el-form-item prop="lan_ip_one">
                <el-input
                  @change="updateFormData.lan_ip = updateFormData.lan_ip_one + updateFormData.lan_ip_two"
                  style="width: 130px"
                  v-model="updateFormData.lan_ip_one"
                  placeholder="请输入IP地址"
                />
              </el-form-item>
              <span>/24</span>
              <span>-</span>
              <el-form-item prop="lan_ip_two">
                <el-input
                  @change="updateFormData.lan_ip = updateFormData.lan_ip_one + updateFormData.lan_ip_two"
                  style="width: 130px"
                  v-model="updateFormData.lan_ip_two"
                  placeholder="请输入IP地址"
                />
              </el-form-item>
              <span>/24</span>
              <el-input type="hidden" :model-value="updateFormData.lan_ip"></el-input>
            </div>
          </el-form-item>
          <el-form-item label="网关" prop="ga_ip" v-else>
            <div class="h-box">
              <el-form-item prop="ga_ip_one">
                <el-input
                  @change="updateFormData.ga_ip = updateFormData.ga_ip_one + updateFormData.ga_ip_two"
                  style="width: 130px"
                  v-model="updateFormData.ga_ip_one"
                  placeholder="请输入IP地址"
                />
              </el-form-item>
              <span>-</span>
              <el-form-item prop="ga_ip_two">
                <el-input
                  @change="updateFormData.ga_ip = updateFormData.ga_ip_one + updateFormData.ga_ip_two"
                  style="width: 130px"
                  v-model="updateFormData.ga_ip_two"
                  placeholder="请输入IP地址"
                />
              </el-form-item>
              <el-input type="hidden" :model-value="updateFormData.ga_ip"></el-input>
            </div>
          </el-form-item>
          <el-divider style="width: calc(100% - 40px); margin: 15px auto" />
          <div style="font-size: 18px; margin-left: 25px">WAN</div>
          <div class="h-box mg-t-lg">
            <el-form-item label="IP" prop="wan_ip">
              <el-input style="width: 130px" v-model="updateFormData.wan_ip" placeholder="请输入IP"></el-input>
            </el-form-item>
            <el-form-item label="掩码" prop="mask">
              <el-input style="width: 130px" v-model="updateFormData.mask" placeholder="请输入掩码"></el-input>
            </el-form-item>
          </div>
          <el-form-item label="网关" prop="gateway">
            <el-input style="width: 130px" v-model="updateFormData.gateway" placeholder="请输入网关"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <template #footer-more-button></template>
  </base-dialog>
</template>

<style lang="scss" scoped>
.update-form {
  display: inline-block;
}
</style>
